package com.mlog.njyjy.ndop.msg.relay.service;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mlog.njyjy.ndop.msg.relay.domain.StandardField;
import com.mlog.njyjy.ndop.msg.relay.util.Constant;
import com.mlog.njyjy.store.kv.core.KvStore;
import com.mlog.njyjy.store.kv.factory.KvStoreFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 加载standard-field.json文件
 *
 * @author zyz
 * @version v1.0, 2020/8/4
 */
@Service
public class ConfigLoaderService implements ApplicationRunner {

    /**
     * 消息校验配置文件
     */
    private static final String STANDARD_FIELD_FILE = "standard-field.json";

    /**
     * 扫描数据文件路径
     */
    private static final ImmutableList<String> SCAN_LOCATIONS = ImmutableList.of("file:cfg/", "file:./config/", "file:./"
            , "classpath:/config/", "classpath:/");


    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    private static ObjectMapper objectMapper = new ObjectMapper();

    private final KvStoreFactory kvStoreFactory;

    private KvStore kvStore;

    public ConfigLoaderService(KvStoreFactory kvStoreFactory) {
        this.kvStoreFactory = kvStoreFactory;
        this.kvStore = kvStoreFactory.getStore();
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String config = loadConfigFromResource();
        if (StrUtil.isNotBlank(config)) {
            kvStore.set(Constant.STANDARD_FIELD_CONFIG, config);
        }
    }

    /**
     * load resource of standard-field.json
     *
     * @return
     */
    private String loadConfigFromResource() throws IOException {
        Resource resource;
        for (String loc : SCAN_LOCATIONS) {
            resource = this.resourceLoader.getResource(loc.concat(STANDARD_FIELD_FILE));
            if (resource.exists()) {
                return new Gson().toJson(objectMapper.readValue(resource.getInputStream(), List.class));
            }
        }
        return null;
    }

    /**
     * get all config
     *
     * @return
     */
    public List<StandardField> getConfig() {
        if (kvStore.has(Constant.STANDARD_FIELD_CONFIG)) {
            String config = kvStore.get(Constant.STANDARD_FIELD_CONFIG);
            return new Gson().fromJson(config,
                    new TypeToken<List<StandardField>>() {
                    }.getType());
        }
        return null;
    }
}
